package com.zzz.dynamicds.utils;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zzz.dynamicds.entity.CompareResult;
import com.zzz.dynamicds.entity.Diff;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ZZZ
 * @version 1.0
 * @date 2019/7/2 0002
 */
public class CommonUtils {

    private CommonUtils(){}

    /**
     * 求两个集合的差集
     * @param old
     * @param newList
     * @return
     */
    public static Set<String> diff(Set<String> old, Set<String> newList) {
        old = old.stream().filter(t -> !newList.contains(t)).collect(Collectors.toSet());
        return old;
    }

    /**
     * 获取字段差异
     * @param tableName
     * @param old
     * @param newList
     * @return
     */
    public static CompareResult getTableDiffs(String tableName, Set<String> old, Set<String> newList) {
        Set<String> diff1 = diff(old, newList);
        List<Diff> diffs = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(diff1)) {
            Diff d1 = new Diff();
            d1.setObjName("old_table");
            d1.setDiffFields(diff1);
            diffs.add(d1);
        }
        Set<String> diff2 = diff(newList, old);
        if (CollectionUtils.isNotEmpty(diff2)) {
            Diff d2 = new Diff();
            d2.setObjName("new_table");
            d2.setDiffFields(diff2);
            diffs.add(d2);
        }
        CompareResult compareResult = new CompareResult();
        compareResult.setTableName(tableName);
        compareResult.setDiffs(diffs);
        return compareResult;
    }


    /**
     * 获取所有表名
     * @return
     */
    public static String[] getAllTableName() {
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        File target = new File(path + "/table_list.txt");
        try {
            String content = FileUtils.readFileToString(target, "utf-8");
            String[] tableArray = content.split("\\r\\n");
            return tableArray;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
